package org.adorsys.aderp.booking.web.ext;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.adorsys.aderp.cash.domain.CashRegItem;
import org.adorsys.aderp.cash.work.encashment.redirect.CashRegItemComponent;
import org.adorsys.aderp.cash.work.encashment.redirect.ClientToAderpCash;
import org.adorsys.aderp.cash.work.encashment.redirect.DataCollection;
import org.adorsys.aderp.cash.work.encashment.redirect.RedirectorBean;
import org.apache.avalon.framework.activity.Suspendable;
import org.apache.commons.lang3.RandomStringUtils;
import org.bouncycastle.asn1.x509.qualified.BiometricData;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

@Controller
@RequestMapping("/bookingtocash")
public class BookingToCashController {
	Logger logger = Logger.getLogger("booking_to_cash_controller");
	
	@Resource
	private ClientToAderpCash bookingToAderpCash;
	
	@Resource
	private RedirectorBean redirectorBean;
	@RequestMapping(method=RequestMethod.GET)
	public String redirect(HttpServletRequest request,HttpServletResponse response,Model uiModel){
		logger.log(Level.INFO, "redirecting ...");
		CashRegItemComponent cashRegItemComponent = new BasicCashRegItemComponent();
		//make a table of keys, to fill data collection.
		String[] keys = {RandomStringUtils.randomAlphanumeric(6),RandomStringUtils.randomAlphanumeric(5),RandomStringUtils.randomAlphabetic(5)};
		List<CashRegItemComponent> firstVague = new ArrayList<CashRegItemComponent>();
		firstVague.add(new BasicCashRegItemComponent(new BigDecimal(2),new BigDecimal(1500)));
		firstVague.add(new BasicCashRegItemComponent(new BigDecimal(8), new BigDecimal(2500)));
		DataCollection dataCollection = new DataCollection();
		dataCollection.addData(keys[0], firstVague);
		dataCollection.addData(keys[1], new BasicCashRegItemComponent(new BigDecimal(5), new BigDecimal(1698)));
		String cashUrl = bookingToAderpCash.getCashUrl("", request, response, cashRegItemComponent,dataCollection );
/*		CashRegItemComponent cashRegItemComponent = new BasicCashRegItemComponent();
		String componentToString = CashRegisterComponentHelper.transformComponentToString(cashRegItemComponent);
		return "redirect:/clienttoaderpcash/processpayment"+encodeUrlPathSegment("?data="+componentToString, request);*/
		return "redirect:"+cashUrl;
	}
	/**
	 * simple implementation of cash register item component
	 * @author w2b
	 *
	 */
	class BasicCashRegItemComponent implements CashRegItemComponent{
		private BigDecimal qty ;
		private BigDecimal unitPrice;
		
		public BasicCashRegItemComponent() {
			this(BigDecimal.ZERO,BigDecimal.ONE);
		}
		public BasicCashRegItemComponent(BigDecimal qty,BigDecimal unitPrice){
			this.qty = qty;
			this.unitPrice = unitPrice;
		}
		@Override
		public String getCashRegItemKey() {
			return UUID.randomUUID().toString();
		}

		@Override
		public BigDecimal getQty() {
			return qty;
		}

		@Override
		public BigDecimal getUnitPrice() {
			return unitPrice;
		}

		@Override
		public BigDecimal getAmount() {
			return getQty().multiply(getUnitPrice());
		}
		
	}
    String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }
    @RequestMapping(value="/sendconversationkeys",method=RequestMethod.GET)
    public String redirectToAderpCash(Model uiModel,HttpServletRequest httpServletRequest,HttpServletResponse response){
    	String collectionKey = RandomStringUtils.randomAlphanumeric(8);
    	CashRegItem cashRegItem = new CashRegItem();
    	cashRegItem.setCashRegItemKey(UUID.randomUUID().toString());
    	cashRegItem.setItemNumber(RandomStringUtils.randomAlphanumeric(8));
    	cashRegItem.setQty(new BigDecimal(4));
    	cashRegItem.setUnitPrice(new BigDecimal(1500));
    	GenericData.getInstance().addCashRegItem(collectionKey,cashRegItem);
    	String callBackUrl = httpServletRequest.getContextPath()+httpServletRequest.getRequestURI();
    	return "redirect:"+redirectorBean.getAderpCashUrl()+"?collectionKey="+collectionKey+"&callbackurl="+callBackUrl;
    }
    @RequestMapping(value="/restfullcallback",method=RequestMethod.GET,headers="Accept=application/json")
    @ResponseBody
    public List<CashRegItem> handleRestFullCallback(@RequestParam("collectionKey")String collectionKey,Model uiModel,HttpServletRequest httpServletRequest,
    		HttpServletResponse httpServletResponse){
    	logger.log(Level.WARNING, "Great ! Successfull CallBack. Request ARRIVED  !! Try To send data to the response ");
    	List<CashRegItem> data = GenericData.getInstance().getData(collectionKey);
    	logger.log(Level.WARNING, "Data Retrieved : "+data.toString());
    	return data;
    }
}
